package com.lzx.applib.okhttp.download;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.lzx.applib.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import static com.lzx.applib.utils.BitmapUtil.TAG;


/**
 * Created by Lzx on 16-12-1.
 */

public class DownloadInfoTable implements TableConstants {

    SQLiteDatabase sql;

    public DownloadInfoTable(Context context) {
        DataBaseHelper helper = new DataBaseHelper(context);
        sql = helper.getReadableDatabase();
    }

    private static boolean init =false;
    private static DownloadInfoTable instance;
    public static void init(Context context) {
        instance = new DownloadInfoTable(context.getApplicationContext());
        init = true;
    }

    public static DownloadInfoTable getInstance() {
        if (!init) throw new IllegalStateException("DownloadInfoTable must be inited before use.");

        return instance;
    }

    public List<DownloadInfo> getAllTask() {
        Cursor cursor = sql.query(TABLE_DOWNLOAD, null, null, null, null, null, null);
        List<DownloadInfo> tasks = new ArrayList<>();
        while (cursor.moveToNext()) {
            DownloadInfo task = new DownloadInfo(cursor);
            tasks.add(task);
        }
        cursor.close();
        return tasks;
    }

    public List<DownloadInfo> getFinishTask() {
        Cursor cursor = sql.query(TABLE_DOWNLOAD, null, STATE + "= ", new String[]{"" + DownloadInfo.FINISH}, null, null, null);
        List<DownloadInfo> tasks = new ArrayList<>();
        while (cursor.moveToNext()) {
            DownloadInfo task = new DownloadInfo(cursor);
            tasks.add(task);
        }
        cursor.close();
        return tasks;
    }

    public DownloadInfo getNextDownloadInfo() {
        Cursor cursor = sql.query(TABLE_DOWNLOAD, null, String.format("%s = ? or %s = ?", STATE, STATE), new String[]{""+DownloadInfo.LOADING, ""+DownloadInfo.WAITING}, null, null, OPERATION_TIME + ASC, "1");
        DownloadInfo info = null;
        if (cursor.moveToNext()) {
            info =  new DownloadInfo(cursor);
        }
        LogUtil.d(TAG, "getNextDownloadInfo", info);
        cursor.close();
        return info;
    }

    public List<DownloadInfo> getUnfinishTask() {
        Cursor cursor = sql.query(TABLE_DOWNLOAD, null, STATE + "!= ?", new String[]{"" + DownloadInfo.FINISH}, null, null, null);
        List<DownloadInfo> tasks = new ArrayList<>();
        while (cursor.moveToNext()) {
            DownloadInfo task = new DownloadInfo(cursor);
            tasks.add(task);
        }
        cursor.close();
        return tasks;
    }

    boolean add(DownloadInfo task) {
        long r = sql.insert(TABLE_DOWNLOAD, null, task.toContentValues());
        return r != -1;
    }

    boolean updateProgress(DownloadInfo task) {
        ContentValues values = new ContentValues();
        values.put(DONE, task.doneBytes);
        values.put(ALL, task.allBytes);
        long r = sql.update(TABLE_DOWNLOAD, values, String.format("%s = ?", REMOTE), new String[]{task.remotePath});
        return r != -1;
    }

    boolean updateState(DownloadInfo task) {
        ContentValues values = new ContentValues();
        values.put(STATE, task.state);
        values.put(OPERATION_TIME, System.currentTimeMillis());
        long r = sql.update(TABLE_DOWNLOAD, values, String.format("%s = ?", REMOTE), new String[]{task.remotePath});
        LogUtil.d(TAG, "updateState() returned: " , r, task);
        return r != -1;
    }

    boolean delete(DownloadInfo task) {
        long r = sql.delete(TABLE_DOWNLOAD, String.format("%s = ?", REMOTE), new String[]{task.remotePath});
        return r != -1;
    }

    public boolean contains(DownloadInfo task) {
        return contains(task.remotePath);
    }

    public boolean contains(String url) {
        Cursor cursor = sql.query(TABLE_DOWNLOAD, null, String.format("%s = ?", REMOTE), new String[]{url}, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count == 1;
    }

    public DownloadInfo getTaskByUrl(String url) {
        DownloadInfo task = null;
        Cursor cursor = sql.query(TABLE_DOWNLOAD, null, String.format("%s = ?", REMOTE), new String[]{url}, null, null, null);
        if (cursor.moveToNext()) {
            task = new DownloadInfo(cursor);
        }
        cursor.close();
        return task;
    }

    class DataBaseHelper extends SQLiteOpenHelper implements TableConstants {

        public DataBaseHelper(Context context) {
            super(context, DATABASE, null, VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            String sql = "create table if not exists %s( %s integer primary key autoincrement," +
                    " %s varchar, %s varcher, %s integer, %s integer, %s varcher, %s varcher, %s integer)";
            sql = String.format(sql, TABLE_DOWNLOAD, ID, REMOTE, LOCAL, DONE, ALL, STATE, OTHER, OPERATION_TIME);
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
    }
}
